package com.community.service.visitor;

import com.community.entity.Visitor;
import com.community.entity.VisitorDetail;
import com.community.entity.VisitorList;
import com.community.mapper.visitor.VisitorMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class VisitorService {

    @Autowired
    private VisitorMapper visitorMapper;

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd");


//1
    public void addVisitor(Visitor visitor) {
        visitor.setId(UUID.randomUUID().toString());
        // 生成 URL
        visitor.setUrl("https://example.com/pass/" + visitor.getId());
        // 生成加密数据
        visitor.setEncryptedData(encryptData(visitor.getId()));
        visitorMapper.insertVisitor(visitor);
    }

    private String encryptData(String input) {
        return Base64.getEncoder().encodeToString((input + "_secure").getBytes());
    }

    public void modifyStatus(String id, String status) {
        visitorMapper.modifyStatus(id, status);
    }


    //自动更新过期访客状态 (status = 0)
    @Scheduled(cron = "0 0 0 * * ?")  // 每天午夜 00:00 运行
    public void updateExpiredVisitors() {
        List<Visitor> visitors = visitorMapper.getAllVisitors();

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date currentDate = calendar.getTime();

        for (Visitor visitor : visitors) {
            try {
                Date visitDate = DATE_FORMAT.parse(visitor.getVisitDate());
                if (visitDate.before(currentDate) && !"0".equals(visitor.getStatus())) {
                    visitorMapper.modifyStatus(visitor.getId(), "0");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }



//2
    public Map<String, Object> getVisitorsWithPagination(int current, int pageSize, String userId) {
        int offset = (current - 1) * pageSize;
        List<VisitorList> visitors = visitorMapper.getVisitorsWithPagination(offset, pageSize,userId);
        int total = visitorMapper.getTotalVisitors(userId);
        int pageTotal = (int) Math.ceil((double) total / pageSize);
        Map<String, Object> response = new HashMap<>();
        response.put("pageTotal", pageTotal);
        response.put("total", total);
        response.put("rows", visitors);
        return response;
    }



//3
    public Map<String, Object> getVisitorDetail(String id) {
        VisitorDetail visitor = visitorMapper.getVisitorDetailById(id);
        if (visitor == null) {
            return null; // 访客不存在
        }

        // 计算剩余有效时间
        long validTime = calculateValidTime(visitor.getVisitDate());
        if (validTime == -1) {
            visitor.setEncryptedData(null);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("id", visitor.getId());
        response.put("houseInfo", visitor.getHouseInfo());
        response.put("url", visitor.getUrl());
        response.put("validTime", validTime);
        response.put("encryptedData", visitor.getEncryptedData());

        return response;
    }

    private long calculateValidTime(String visitDateStr) {
        try {
            LocalDate visitDate = LocalDate.parse(visitDateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDateTime visitEndDateTime = visitDate.plusDays(1).atStartOfDay();
            long visitEndTime = visitEndDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
            long currentTime = System.currentTimeMillis();

            if (visitEndTime < currentTime) {
                return -1; // 已失效
            } else {
                return (visitEndTime - currentTime) / 1000; // 剩余秒数
            }
        } catch (Exception e) {
            return -1;
        }
    }



//4
    public Map<String, Object> getVisitorDetailByEncryptedData(String encryptedData) {
        VisitorDetail visitor = visitorMapper.getVisitorByEncryptedData(encryptedData);
        if (visitor == null) {
            return null; // 访客不存在
        }

        long validTime = calculateValidTime(visitor.getVisitDate());
        Map<String, Object> response = new HashMap<>();
        response.put("id", visitor.getId());
        response.put("houseInfo", visitor.getHouseInfo());
        response.put("url", visitor.getUrl());
        response.put("validTime", validTime);

        return response;
    }

}
